<?php

$status = false;
$errors = array();

require_once 'library/config.php';

function __autoload($class_name) {
    include_once 'library/' . strtolower($class_name) . '.php';
}

$facebook = new Facebook(array(
            'appId' => FB_ID,
            'secret' => FB_SECRET,
        ));

$request = $facebook->getSignedRequest();

if ($request) {
    $register = $request['registration'];

    try {

        $db = Db::init();

        $fbId = (isset($request['user_id'])) ? $request['user_id'] : 0;
        $user = new User();

        // User tries to register again with the same Facebook ID
        if ($fbId != 0) {
            if ($user->fbLogin($fbId)) {
                header('Location: index.php');
                exit();
            }
        }

        $sth = $db->prepare("SELECT * FROM users WHERE username = ?");
        $sth->execute(array($register['username']));

        if (!$sth->fetch()) {
            $sth = $db->prepare("SELECT * FROM users WHERE email = ?");
            $sth->execute(array($register['email']));

            if ((false != $sth->fetch()) && ($fbId != 0)) {
                $sth = $db->prepare("UPDATE users SET facebook = ? WHERE email = ?");
                if ($sth->execute(array($fbId, $register['email']))) {
                    // This is new. Try to login the user using Facebook ID
                    $status = $user->fbLogin($fbId);
                }
            } else {
                $location = $register['location'];
                if (is_array($location)) {
                    $location = $location['name'];
                }

                $sql = "INSERT INTO users
                                (facebook, username, password, name, email, location, gender, ip)
                            VALUES
                                (?, ?, ?, ?, ?, ?, ?, ?)";

                $data = array(
                    $fbId,
                    $register['username'],
                    md5($register['password']),
                    $register['name'],
                    $register['email'],
                    $location,
                    $register['gender'],
                    $_SERVER['REMOTE_ADDR']
                );

                $sth = $db->prepare($sql);
                if ($sth->execute($data)) {
                    // Login user immediately using username and password
                    $status = $user->login($register['username'], $register['password']);
                }
            }
        } else {
            array_push($errors, 'Username is already taken!');
        }
    } catch (Exception $e) {
        array_push($errors, 'Database error: ' . $e->getMessage());
    }
} else {
    array_push($errors, 'Error with validating Signed request.');
}

if (true === $status) {
    echo 'User registered successfully';
} else {
    echo 'Errors during registration:';
    if (!empty($errors)) {
        echo '<ul>';

        foreach ($errors as $e) {
            echo '<li>' . $e . '</li>';
        }

        echo '</ul>';
    }
}